<template>
  <el-form
    ref="ruleForm"
    :label-width="labelWidth"
    :model="form"
    :rules="rules"
  >
    <el-form-item :label="desc" prop="addressCode">
      <el-cascader
        ref="cascader"
        v-model="form.addressCode"
        style="width: 100%"
        clearable
        size="small"
        :placeholder="placeHoleder ? placeHoleder : placeholderText"
        :show-all-levels="true"
        :options="addressData"
        :props="props"
        @change="handleChange"
      />
    </el-form-item>
  </el-form>
</template>

<script>
import { getAddress } from "@/api/public";

export default {
  props: {
    // 是否必填
    isRequire: {
      type: Boolean,
      isRequire: false,
      default: false,
    },
    // 描述字段
    desc: {
      type: String,
      isRequire: false,
      default: "省市区",
    },
    // 联动最大层级
    leaf: {
      type: Number,
      isRequire: false,
      default: 2,
    },
    // 是否可选择任意一级节点
    checkStrictly: {
      type: Boolean,
      isRequire: false,
      default: true,
    },
    placeHoleder: {
      type: String,
      isRequire: false,
      default: "请选择地址",
    },

    //字段对应的key值
    name: {
      type: String,
      isRequire: false,
      default: "addressCode",
    },

    //labelwidth长度
    labelWidth: {
      type: String,
      isRequire: false,
      default: "120px",
    },
  },
  data() {
    return {
      // 表单校验规则
      rules: {
        addressCode: [
          {
            required: this.isRequire,
            message: this.desc + "不能为空",
            trigger: "change",
          },
        ],
      },
      form: {
        addressCode: [], // 选定的地址编码
      },

      addressData: [], // 地址选择初始化数据
      props: {
        checkStrictly: this.checkStrictly,
        label: "name",
        value: "code",
        children: "child",
        lazy: true,
        lazyLoad: (node, resolve) => {
          const { level } = node;
          // 处理数据
          const handlerData = (res) => {
            resolve(
              res.map((val) => {
                return {
                  name: val.name,
                  code: val.code,
                  child: val.child,
                  leaf: level >= this.leaf,
                };
              })
            );
          };

          if (level !== 0) {
            const nodeId = node.data.code;
            getAddress({ parentCode: nodeId }).then((res) => {
              const oldAddressData = res.data.map((item, index, arry) => {
                return Object.assign(item, { child: [] });
              });
              const newAddress = Array.from(oldAddressData);
              handlerData(newAddress);
            });
          }
        },
      },
    };
  },
  computed: {
    placeholderText() {
      let realText;
      switch (this.leaf) {
        case 0:
          realText = "请选择省";
          break;
        case 1:
          realText = "请选择省/市";
          break;
        case 2:
          realText = "请选择省/市/区";
          break;
        case 3:
          realText = "请选择省/市/区/街道";
          break;

        default:
          break;
      }

      return realText;
    },
  },
  watch: {
    // 选定地址后，选择框自动收起
    "form.addressCode"() {
      if (this.$refs.cascader) {
        this.$refs.cascader.dropDownVisible = false;
      }
    },
  },
  created() {
    // 获取省份地址
    getAddress({ parentCode: 0 }).then((res) => {
      this.provinceOpt = res.data;
      const oldAddressData = res.data.map((item, index, arry) => {
        return Object.assign(item, { child: [] });
      });

      const newAddress = Array.from(oldAddressData);
      this.addressData = newAddress;
    });
  },
  methods: {
    handleChange(value) {
      this.$nextTick(() => {
        // 切割成数组并去除空格
        let AddressName =
          this.$refs.cascader.presentText &&
          this.$refs.cascader.presentText.split("/").map((item) => item.trim());
        this.$emit("chooseAddress", {
          codeList: value,
          textList: AddressName,
          name: this.name,
        });
      });
    },

    // 地址选择组件表单验证
    validate() {
      let flag;
      this.$refs.ruleForm.validate((valid) => (flag = valid));
      return flag;
    },

    // 清除选择框的数据
    clearData() {
      this.form.addressCode = [];
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form {
  width: 100%;
  display: flex;
  align-items: center;
}

::v-deep .el-form-item__content {
  display: flex;
  flex: 1;
  margin-left: 0 !important;
}

::v-deep .el-cascader-panel {
  height: 400px;
}
</style>
